//
//  SEGWKWebViewController.m
//  Pods-SEGWebView_Example
//
//  Created by 刘山 on 2020/3/5.
//
#import "SEGWKWebViewController.h"
#import "SEGWeakWebViewScriptMessageDelegate.h"
#import "SEGWebViewConsts.h"
#import "NSString+WKAdd.h"
#import "SEGWKWebBottomView.h"
#import "SEGWKWebNavigationView.h"
#import "NSDictionary+WKAdd.h"

typedef NS_ENUM(NSUInteger, SEGWKWebViewNavigationBarType) {
    SEGWKWebViewNavigationBarTypeShow,
    SEGWKWebViewNavigationBarTypeHide,
    SEGWKWebViewNavigationBarTypeClearColor
};

@interface SEGWKWebViewController ()<WKNavigationDelegate,WKUIDelegate,UIScrollViewDelegate,WKScriptMessageHandler,UIAlertViewDelegate>

/// bottom view
@property (nonatomic, strong)SEGWKWebBottomView *bottomView;

/// navigationbar
@property (nonatomic, strong)SEGWKWebNavigationView *navigationbar;

/// 分享URL参数数据
@property (nonatomic, copy) NSString *setShareUrlString;

@end

@implementation SEGWKWebViewController
#pragma mark - 初始化
-(instancetype)initWithConfig:(SEGWebViewConfig*)config{
    if (self == [super init]) {
        _webViewConfig = config;
    }
    return self;
}
#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self segAddSubview];
    [self segSetWebConfig];
    [self segAddKVO];
    [self segAddNotifications];
    
    [self updateNavigationBarWithType:SEGWKWebViewNavigationBarTypeHide];
    self.linkURL = [self loadDataWithURLString:self.linkURL];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self loadCbUrlString];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    [self.progressView setFrame:CGRectMake(0, 0, WK_SCREEN_WIDTH(), 2)];
    [self.bottomView setFrame:CGRectMake(0, WK_SCREEN_HEIGHT() - WK_TabAndSafeBottomHeight(), WK_SCREEN_WIDTH(), WK_TabAndSafeBottomHeight())];
    [self.navigationbar setFrame:CGRectMake(0, 0, WK_SCREEN_WIDTH(), WK_StatusBarAndNaviBarHeight())];
}

- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
    [self.webView removeObserver:self forKeyPath:@"canGoForward"];
}

#pragma mark - 实现父类抽象方法

-(void)segAddSubview {
    [super segAddSubview];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.navigationbar];
}

-(void)segAddKVO{
    [super segAddKVO];
    [self.webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];
}

-(void)segAddNotifications{
    [super segAddNotifications];
}

-(BOOL)jsInvokeSystemFunctionWithWebView:(WKWebView *)webView request:(NSURLRequest *)request query:(NSString *)query{
    NSString * scheme = request.URL.scheme;
    NSString * host = request.URL.host;
    
    // 基于：window.location.href拦截JS协议，唤起原生方法
    if (scheme && host && [scheme rangeOfString:@"uhomeoc"].location != NSNotFound){
        // 隐藏原生头部导航栏
        if ([host rangeOfString:@"system.hideHeader"].location != NSNotFound) {
            [self segJSSystemHideHeader];
            return NO;
        }
        if ([host rangeOfString:@"homeservice.setHeadTitle"].location != NSNotFound){ // 到家服务-设置标题栏标题，选中状态
            [self segJSHomeserviceSetHeadTitleWithQuery:query];
            return NO;
        }
        // 第三方使用api：返回native界面
        if ([host rangeOfString:@"thirdparty.goBack"].location != NSNotFound) {
            [self segJSThirdpartyGoBackWithQuery:query];
            return NO;
        }
        // 第三方使用api：弹出确认框
        if ([host rangeOfString:@"thirdparty.openDialog"].location != NSNotFound) {
            [self segJSThirdpartyOpenDialogWithQuery:query];
            return NO;
        }
        // 使用原生系统功能：把字符串添加到系统剪贴板
        if ([host rangeOfString:@"system.addToClipboard"].location != NSNotFound) {
            [self segJSSystemAddToClipboardWithQuery:query];
            return NO;
        }
        // 获取cookie
        if (([host rangeOfString:@"system.getCookie"].location != NSNotFound)||[host rangeOfString:@"system.getSysCookie"].location != NSNotFound) {
            [self segJSGetCookieWithQuery:query];
            return NO;
        }
        // 设置分享参数
        if ([host rangeOfString:@"homeservice.setSharePara"].location != NSNotFound){
            _setShareUrlString = query;
            return NO;
        }
        
        // 第三方使用api：跳转到支付列表
        if ([host rangeOfString:@"thirdparty.goPayList"].location != NSNotFound) {
            [self segJSThirdpartyGoPayListWithQuery:query];
        }
        // 第三方使用api：支付
        if ([host rangeOfString:@"thirdparty.pay"].location != NSNotFound) {
            [self segJSThirdpartyPayWithQuery:query];
        }
    }
    // 子类调用的方法，实现与业务挂钩
    return [super jsInvokeSystemFunctionWithWebView:webView request:request query:query];
}

-(NSString*)segReplaceUrlStringWithUrlString:(NSString *)urlString {
    return [super segReplaceUrlStringWithUrlString:urlString];
}
-(NSString*)getUrlStringWithAppPlatformCode:(NSString *)urlString {
    return [super getUrlStringWithAppPlatformCode:urlString];
}

#pragma mark - 父类方法
-(void)segShare:(NSString*)query{}

#pragma mark - 私有方法

-(void)segSetWebConfig{
    self.progressView.tintColor = self.webViewConfig.progressColor;
    
    self.bottomView.backgroundColor = self.webViewConfig.tabBarBackGroundColor;
    self.bottomView.lineView.backgroundColor = self.webViewConfig.lineColor;
    self.bottomView.closeButton.tintColor = self.webViewConfig.bottomItemsColor;
    self.bottomView.shareButton.tintColor = self.webViewConfig.bottomItemsColor;
    self.bottomView.reloadButton.tintColor = self.webViewConfig.bottomItemsColor;
    
    self.navigationbar.backgroundColor = self.webViewConfig.navigationBarGroundColor;
    self.navigationbar.lineView.backgroundColor = self.webViewConfig.lineColor;
    self.navigationbar.titleColor = self.webViewConfig.navigationBarTitleColor;
}

/// 更新底部视图 goBack按钮的状态
-(void)updateBottomViewGoBackButtonStatus {
    if ([self.webView canGoBack]) {
        self.bottomView.goBackButton.enabled = YES;
        self.bottomView.goBackButton.tintColor = self.webViewConfig.bottomItemsColor;
    }else{
        self.bottomView.goBackButton.enabled = NO;
        self.bottomView.goBackButton.tintColor = self.webViewConfig.bottomItemsDisableColor;
    }
}

/// 更新底部视图goForward 按钮的状态
-(void)updateBottomViewGoForwardButtonStatus {
    if ([self.webView canGoForward]) {
        self.bottomView.goForwardButton.enabled = YES;
        self.bottomView.goForwardButton.tintColor = self.webViewConfig.bottomItemsColor;
    }else{
        self.bottomView.goForwardButton.enabled = NO;
        self.bottomView.goForwardButton.tintColor = self.webViewConfig.bottomItemsDisableColor;
    }
}

-(void)updateNavigationBarWithType:(SEGWKWebViewNavigationBarType)showType{
    // 展示自定义导航栏布局
    if (showType == SEGWKWebViewNavigationBarTypeShow) {
        [self.navigationbar setHidden:NO];
        [self.webView setFrame:CGRectMake(0, WK_StatusBarAndNaviBarHeight(), WK_SCREEN_WIDTH(), WK_SCREEN_HEIGHT() - WK_TabAndSafeBottomHeight() - WK_StatusBarAndNaviBarHeight())];
        return;
    }
    // 隐藏自定义导航栏布局
    if (showType == SEGWKWebViewNavigationBarTypeHide) {
        [self.navigationbar setHidden:YES];
        [self.webView setFrame:CGRectMake(0, WK_StatusBarHeight(), WK_SCREEN_WIDTH(), WK_SCREEN_HEIGHT() - WK_TabAndSafeBottomHeight() - WK_StatusBarHeight())];
        return;
    }
    // 自定义导航栏布局-设置透明
    if (showType == SEGWKWebViewNavigationBarTypeClearColor) {
        [self.navigationbar setHidden:NO];
        [self.webView setFrame:CGRectMake(0, 0, WK_SCREEN_WIDTH(), WK_SCREEN_HEIGHT() - WK_TabAndSafeBottomHeight())];
        return;
    }
}


#pragma mark - KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if (object == self.webView && [keyPath isEqualToString:@"canGoBack"]){
        [self updateBottomViewGoBackButtonStatus];
    }else if (object == self.webView && [keyPath isEqualToString:@"canGoForward"]){
        [self updateBottomViewGoForwardButtonStatus];
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - 集成部分JS协议
/**
 使用原生系统功能：隐藏原生头部导航栏
 处理：隐藏原生头部导航栏
 
 空
 
 @author Sam
 */
-(void)segJSSystemHideHeader{
    [self updateNavigationBarWithType:SEGWKWebViewNavigationBarTypeHide];
}


/// 根据参数设置标题栏
/// @param query {"isTransparent":0,"title":"测试","urls":"","selected":1,"hasShare":0,"fn":"uhomeNativeApi.thirdParty.setHeadTitleCb"}
-(void)segJSHomeserviceSetHeadTitleWithQuery:(NSString*)query{
    /*
     入参：
     isTransparent:1/0 //1为透明，0为非透明样式
     title:”aaa,bbb,cccc”//设置导航栏标题，有可能多个 逗号隔开
     urls:”afsdsdf.com,dfsdfas.com,ccc.com”//上面标题对应的跳转路径
     selected:1 //选中的标题，按按照顺序，从1开始
     hasShare:1/0 // 1为显示转发按钮，0为不显示
     fn:”fn”//返回函数
     
     出参：
     code:0，//1为成功，0为失败
     message:”XXXX”//提示语
     */
    NSDictionary *params = [query toDictionary];
    if (!(params && [params isKindOfClass:[NSDictionary class]])) return;
    
    NSString *isTransparent = [params valueForKey:@"isTransparent"];
    NSString *title = [params valueForKey:@"title"];
    NSString *urls = [params valueForKey:@"urls"];
    NSString *selected = [params valueForKey:@"selected"];
    NSString *hasShare = [params valueForKey:@"hasShare"];
    NSString *fn = [params valueForKey:@"fn"];
    
    isTransparent = isTransparent ? [NSString toString:isTransparent]: @"";
    title = title ? [NSString toString:title]: @"";
    urls = urls ? [NSString toString:urls]: @"";
    selected = selected ? [NSString toString:selected]: @"";
    hasShare = hasShare ? [NSString toString:hasShare]: @"";
    fn = fn ? [NSString toString:fn]: @"";
    
    if ([isTransparent isEqualToString:@"1"]) {// 透明
        [self updateNavigationBarWithType:SEGWKWebViewNavigationBarTypeHide];
    }else{
        [self updateNavigationBarWithType:SEGWKWebViewNavigationBarTypeShow];
        if (title.length >0) {
            self.navigationbar.title = title;
        }
    }
    
    [self.bottomView.shareButton setHidden:[hasShare isEqualToString:@"1"] ? NO : YES];
    
    NSString *javaScript = [NSString stringWithFormat:@"%@(%@)",fn,[@{@"code":@"1",@"message":@""} toJsonString]];
    [self.webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable req, NSError * _Nullable error) {
    }];
}

/// 跳转到相关的原生页面，兼容ios 需传参 type
/// @param query {"type":"native"}
-(void)segJSThirdpartyGoBackWithQuery:(NSString*)query{
    [self.navigationController popViewControllerAnimated:YES];
}


/// 弹出确认框，返回用户选择的操作
/// @param query params={"title":"title","content":"content test","type":0,"fn":"uhomeNativeApi.thirdParty.openDialogCb"}
-(void)segJSThirdpartyOpenDialogWithQuery:(NSString*)query{
    /*
     入参:
     Key:fn Value:’XXXX’//返回函数名
     Key: title Value:’XXXX’//标题
     Key: content Value:’XXXX’//提示内容
     Key: type Value: 0 // 有取消 有确定; 1 只有确定； 2 只有取消。 默认0
     
     出参:
     code:1，//1为成功，0为失败
     message:”XXXX”//提示语
     data: 1/0 //0为取消1为确认
     */
    NSDictionary *params = [query toDictionary];
    if (!(params && [params isKindOfClass:[NSDictionary class]])) return;
    NSString *title = [params valueForKey:@"title"];
    NSString *content = [params valueForKey:@"content"];
    NSString *fn = [params valueForKey:@"fn"];
    NSString *type = [params valueForKey:@"type"];
    
    title = title ? [NSString toString:type] : @"";
    content = content ? [NSString toString:content] : @"";
    fn = fn ? [NSString toString:fn] : @"";
    type = type ? [NSString toString:type] : @"";
    
    UIAlertView *alert;
    if ([type isEqualToString:@"1"]) {
        alert = [[UIAlertView alloc] initWithTitle:title message:content delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    }else if ([type isEqualToString:@"2"]){
        alert = [[UIAlertView alloc] initWithTitle:title message:content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    }else{
        alert = [[UIAlertView alloc] initWithTitle:title message:content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    [alert show];
}

/// 把字符串添加到系统剪贴板
-(void)segJSSystemAddToClipboardWithQuery:(NSString*)query{
    NSDictionary *params = [query toDictionary];
    if (!(params && [params isKindOfClass:[NSDictionary class]])) return;
    NSString *string = [params valueForKey:@"string"];
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = string;
}

- (void)segJSGetCookieWithQuery:(NSString *)query {
    NSDictionary *params = [query toDictionary];
    if (!(params && [params isKindOfClass:[NSDictionary class]])) return;
    NSString *fn = [params valueForKey:@"fn"];
    
    fn = fn ? [NSString toString:fn] : @"";
    
    NSArray *cookies = [[NSHTTPCookieStorage  sharedHTTPCookieStorage] cookies];
    NSDictionary * cookiesDic = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    NSString *cookieString = cookiesDic[@"Cookie"] ?: @"";
    NSDictionary *result = @{@"code":@(1), @"data": cookieString};
    NSString* jsonStr = [result toJsonString];
    NSString *str = [NSString stringWithFormat:@"%@(%@)",fn,jsonStr];
    NSString *javaScript = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    [self.webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable response, NSError * _Nullable error) {
    }];
}

-(void)segJSThirdpartyGoPayListWithQuery:(NSString*)query{
    NSDictionary *params = [query toDictionary];
    if (!(params && [params isKindOfClass:[NSDictionary class]])) return;
    NSString *cbUrl = [params valueForKey:@"cbUrl"];
    self.cbUrlString = cbUrl;
}

-(void)segJSThirdpartyPayWithQuery:(NSString*)query{
    NSDictionary *params = [query toDictionary];
    if (!(params && [params isKindOfClass:[NSDictionary class]])) return;
    NSString *cbUrl = [params valueForKey:@"cbUrl"];
    self.cbUrlString = cbUrl;
}

#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (self.current_uhomeoc_href) {
        NSString * query = [self.current_uhomeoc_href.query wkStringByURLDecode];
        if ([self.current_uhomeoc_href.absoluteString rangeOfString:@"params="].location != NSNotFound) {
            query = [[self.current_uhomeoc_href.absoluteString componentsSeparatedByString:@"params="].lastObject wkStringByURLDecode];
        }
        
        if ([self.current_uhomeoc_href.host rangeOfString:@"thirdparty.openDialog"].location != NSNotFound) {
            NSDictionary *params = [query toDictionary];
            if (!(params && [params isKindOfClass:[NSDictionary class]])) return;
            
            NSString *title = [params valueForKey:@"title"];
            NSString *content = [params valueForKey:@"content"];
            NSString *fn = [params valueForKey:@"fn"];
            NSString *type = [params valueForKey:@"type"];//0 有取消 有确定; 1 只有确定； 2 只有取消。 默认0
            
            title = title ? [NSString toString:type] : @"";
            content = content ? [NSString toString:content] : @"";
            fn = fn ? [NSString toString:fn] : @"";
            type = type ? [NSString toString:type] : @"";
            
            NSMutableDictionary *ret = [NSMutableDictionary dictionary];
            [ret setObject:@"1" forKey:@"code"];//1为成功，0为失败
            [ret setObject:content forKey:@"message"]; //提示语
            [ret setObject:content forKey:@"message"]; //提示语
            
            if ([type isEqualToString:@"1"]) { //type=1,只有确定按钮，返回data：1
                [ret setObject:@"1" forKey:@"data"];
            }else if ([type isEqualToString:@"2"]){ //type=2,只有取消按钮，返回data：0
                [ret setObject:@"0" forKey:@"data"];
            }else{
                if (buttonIndex == 0){
                    [ret setObject:@"0" forKey:@"data"];
                }else{
                    [ret setObject:@"1" forKey:@"data"];
                }
            }
            NSString *jsString = [NSString stringWithFormat:@"%@(%@)",fn,[ret toJsonString]];
            [self.webView evaluateJavaScript:jsString completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            }];
        }
    }
}

#pragma mark - BottomView Click Events
-(void)goBackClick:(UIButton*)sender{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }
}

-(void)goForwardClick:(UIButton*)sender{
    if ([self.webView canGoForward]) {
        [self.webView goForward];
    }
}

-(void)closeClick:(UIButton*)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)shareClick:(UIButton*)sender{
    [self segShare:self.setShareUrlString];
}

-(void)reloadClick:(UIButton*)sender{
    [self.webView reload];
}

-(void)testClick:(UIButton*)sender{
    [self loadDataWithURLString:@"https://www.msnewlifefitness.com/web/test.html"];
}

#pragma mark - getter
-(SEGWKWebBottomView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[SEGWKWebBottomView alloc] initWithFrame:CGRectZero];
        [_bottomView.goBackButton addTarget:self action:@selector(goBackClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.goForwardButton addTarget:self action:@selector(goForwardClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.closeButton addTarget:self action:@selector(closeClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.shareButton addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.reloadButton addTarget:self action:@selector(reloadClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.testButton addTarget:self action:@selector(testClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomView;
}

-(SEGWKWebNavigationView *)navigationbar{
    if (!_navigationbar) {
        _navigationbar = [[SEGWKWebNavigationView alloc] initWithFrame:CGRectZero];
//        [_navigationbar.closeButton addTarget:self action:@selector(closeClick:) forControlEvents:UIControlEventTouchUpInside];
//        [_navigationbar.shareButton addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
//        [_navigationbar.reloadButton addTarget:self action:@selector(reloadClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _navigationbar;
}
//-(NSURL *)current_uhomeoc_href{
//    if (!_current_uhomeoc_href) {
//        _current_uhomeoc_href = [[NSURL alloc] init];
//    }
//    return _current_uhomeoc_href;
//}
@end
